package com.southwind.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.southwind.entity.Record;
import com.southwind.mapper.RecordMapper;
import com.southwind.mapper.UserMapper;
import com.southwind.vo.PageVO;
import com.southwind.vo.RecordVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/record")
public class RecordController {

    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/save")
    public Integer save(@RequestBody Record record){
        record.setUid(UserController.USER.getId());
        record.setCreateTime(new Date());
        return this.recordMapper.insert(record);
    }

    @GetMapping("/list")
    public PageVO list(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size,
            @RequestParam(value = "keyWord",required = false) String keyWord,
            @RequestParam(value = "type",required = false) String type,
            @RequestParam(value = "date",required = false) String date
    ){
        Page<Record> pageModel = new Page<>(page, size);
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(keyWord) && StringUtils.isNotBlank(type),type,keyWord);
        if(date != null){
            date = date.substring(0, 10)+" 00:00:00";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date startTime = sdf.parse(date);
                date = date.substring(0, 10)+" 23:59:59";
                Date endTime = sdf.parse(date);
                queryWrapper.between(StringUtils.isNotBlank(date),"create_time",startTime,endTime);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        queryWrapper.eq("uid",UserController.USER.getId());
        Page<Record> resultPage = this.recordMapper.selectPage(pageModel, queryWrapper);
        List<RecordVO> list = new ArrayList<>();
        for (Record record : resultPage.getRecords()) {
            RecordVO recordVO = new RecordVO();
            BeanUtils.copyProperties(record, recordVO);
            recordVO.setUsername(this.userMapper.selectById(record.getUid()).getUsername());
            list.add(recordVO);
        }
        return new PageVO(list,resultPage.getSize(),resultPage.getTotal());
    }

    @DeleteMapping("/delete/{id}")
    public Integer delete(@PathVariable("id") Integer id){
        return this.recordMapper.deleteById(id);
    }
}
